package org.pliers.web.execptionHandler;

import com.fasterxml.jackson.core.JsonProcessingException;


import org.pliers.Mappers;
import org.pliers.exception.BusinessException;
import org.pliers.web.HttpErrorCode;
import org.pliers.web.RestResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;


public class RepositoryResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {
    private Logger log = LoggerFactory.getLogger(getClass());

    @ExceptionHandler(BusinessException.class)
    protected ResponseEntity<Object> handleExceptions(Exception e, WebRequest request) throws JsonProcessingException {
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/json;charset=UTF-8");
        RestResult<String> restResult = new RestResult<String>(((BusinessException) e).code, ((BusinessException) e).desc);
        String body = Mappers.objectMapper.writeValueAsString(restResult);
        log.warn(body);
        return ResponseEntity
                .status(HttpErrorCode.BUSINESSEXCEPTION_HTTPSTATUS.code)
                .headers(headers)
                .body(body);
    }


}